<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-包装入库申请`"
		width="1300px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 2" label-width="110px" :show-message="false">
			<div ref="box1">
				<div class="flex-start-center margin-bottom-4" style="font-size: 13px;">
					<el-tag v-if="!ruleForm.code" type="primary" effect="plain" class="">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div v-else style="font-size: 16px;">
						<span class="el-icon-star-off item-gap"></span>
						<span>{{ ruleForm.code || '系统自动生成' }}</span>
					</div>
				</div>
				<jk-card>
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="区域">
								<span class="read-only-2">{{ ruleForm.workshopName }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="申请日期">
								<span class="read-only-2">{{ ruleForm.belongDate }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="仓库" prop="warehouseId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 2" class="read-only-2">{{ ruleForm.warehouseName }}</span>
								<jk-select v-else v-model="ruleForm.warehouseId" :option-list="warehouseList" class="width-100-percent" size="medium" placeholder="仓库" @change="onWarehouseChange" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="入库类别" prop="typeId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 2" class="read-only-2">{{ ruleForm.typeName }}</span>
								<jk-select v-else v-model="ruleForm.typeId" :option-list="typeList" class="width-100-percent" size="medium" placeholder="入库类别" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="部门" prop="deptId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 2" class="read-only-2">{{ ruleForm.deptName }}</span>
								<jkCascader v-else v-model="ruleForm.deptId" :option-list="deptList" class="width-100-percent" size="medium" placeholder="部门" @change="onDeptChange" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="销售地点">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 2" class="read-only-2">{{ ruleForm.saleAddress }}</span>
								<jk-input v-else v-model="ruleForm.saleAddress" class="width-100-percent" size="medium" placeholder="销售地点" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 2" class="read-only-2">{{ ruleForm.remark }}</span>
								<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placeholder="请输入..." />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
				<el-tag class="margin-bottom-4 el-icon-tickets margin-top-10" effect="plain">订单明细</el-tag>
			</div>
			<jk-table border :data="ruleForm.packageInStorageItemList" :height="dialogTableHeight - 20">
				<vxe-column type="expand" title="展开" align="center" :width="54">
					<template #content="scope">
						<el-row class="flex-start-center-wrap margin-top-10" style="padding-right: 10px;padding-bottom: 10px;">
							<el-col :span="6">
								<el-form-item class="margin-bottom-0" label="纸管颜色:">
									<span>{{ scope.row.paperTubeList ? scope.row.paperTubeList.map(x => x.name).join(',') : '' }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item class="margin-bottom-0" label="腰绳颜色:">
									<span>{{ scope.row.waistPopeList ? scope.row.waistPopeList.map(x => x.name).join(',') : '' }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item class="margin-bottom-0" label="标签颜色:">
									<span>{{ scope.row.labelColorList ? scope.row.labelColorList.map(x => x.name).join(',') : '' }}</span>
								</el-form-item>
							</el-col>
						</el-row>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" field="operation" :width="64">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" icon="el-icon-minus" @click="ruleForm.packageInStorageItemList.splice(scope.rowIndex, 1)" />
						</div>
					</template>
				</vxe-column>
				<vxe-column title="生产订单" align="left" field="productOrderCode" :width="144"></vxe-column>
				<vxe-column title="品种" align="left" field="productName" :min-width="140"></vxe-column>
				<vxe-column title="批号" align="left" field="batchCode" :width="100"></vxe-column>
				<!--<vxe-column title="纸管颜色" align="left" field="unitPrice" :min-width="100">
					<template slot-scope="scope">
						<span>{{ scope.row.paperTubeList ? scope.row.paperTubeList.map(x => x.name).join(',') : '' }}</span>
					</template>
				</vxe-column>
				<vxe-column title="腰绳颜色" align="left" field="waistPopeList" :min-width="100">
					<template slot-scope="scope">
						<span>{{ scope.row.waistPopeList ? scope.row.waistPopeList.map(x => x.name).join(',') : '' }}</span>
					</template>
				</vxe-column>
				<vxe-column title="标签颜色" align="left" field="unitPrice" :min-width="100">
					<template slot-scope="scope">
						<span>{{ scope.row.labelColorList ? scope.row.labelColorList.map(x => x.name).join(',') : '' }}</span>
					</template>
				</vxe-column>-->
				<vxe-column title="报工数量" align="right" field="reportQty" :width="80"></vxe-column>
				<vxe-column title="已入库" align="right" field="packWarehousingNum" :width="70"></vxe-column>
				<vxe-column title="待入库" align="right" field="packWaitWarehousingNum" :width="70"></vxe-column>
				<vxe-column title="申请数" align="right" field="inPackageQty" :width="60"></vxe-column>
				<vxe-column title="活码" align="right" field="packLiveCode" :width="60"></vxe-column>
				<vxe-column title="销售订单" align="left" field="unitPrice" :min-width="400">
					<template slot="header">
						<el-row :gutter="6">
							<el-col :span="7">销售单号</el-col>
							<el-col :span="3" class="flex-end-center">已入库</el-col>
							<el-col :span="8">货位</el-col>
							<el-col :span="6">入库数</el-col>
						</el-row>
					</template>
					<template slot-scope="scope">
						<el-row
							v-for="(saleOrderItem, saleOrderIndex) in scope.row.saleOrderList || [{}, {}, {}]"
							:key="saleOrderIndex"
							:gutter="6"
							class="flex-start-center"
						>
							<el-col :span="7">
								<span>{{ saleOrderIndex + 1 }}、{{ saleOrderItem.saleOrderCode || '无' }}</span>
							</el-col>
							<el-col class="flex-end-center" :span="3">
								<span>{{ saleOrderItem.inPackageQty || '0' }}</span>
							</el-col>
							<el-col :span="8">
								<jk-select v-model="saleOrderItem.positionId" :disabled="!ruleForm.warehouseId" :option-list="positionList" placeholder="货位" size="mini" class="width-100-percent"></jk-select>
							</el-col>
							<el-col :span="6" class="flex-start-center">
								<jk-number-input v-model="saleOrderItem.inQty" placeholder="入库数" size="mini" class="width-100-percent"></jk-number-input>
								<div class="el-icon-remove delete-icon" @click="onDeleteSaleOrderBtn(scope.rowIndex, saleOrderIndex)"></div>
							</el-col>
						</el-row>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionPackageInStorageUpdate,
        productionPackageInStorageGet,
        spinWarehousePage, spinPositionPage
    } from '../../../../api/production/package';
    import remoteSearchProductInput from '../../../technology/order/components/remote-search-product-input';
    import { formatDate } from '../../../../utils/jk/jk-tool';
    import jkCascader from './components/jk-cascader';
    import { listDept } from '../../../../api/system/dept';
    export default {
        mixins: [calHeight],
        components: { jkCascader, remoteSearchProductInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'belongDate': '',
                    'code': '',
                    'deptCode': '',
                    'deptId': 223,
                    'deptName': '',
                    'packageInStorageItemList': [
                        {
                            'batchCode': '',
                            'id': null,
                            'inPackageQty': null,
                            'inQty': null,
                            'labelColorList': '',
                            'packLiveCode': null,
                            'packWaitWarehousingNum': null,
                            'packWarehousingNum': null,
                            'paperTubeList': '',
                            'positionCode': '',
                            'positionId': null,
                            'positionName': '',
                            'productCode': '',
                            'productId': null,
                            'productName': '',
                            'productOrderCode': '',
                            'productOrderId': null,
                            'productionAddress': '',
                            'productionInDate': '',
                            'remark': '',
                            'reportQty': null,
                            'unitCode': '',
                            'unitId': null,
                            'unitName': '',
                            'waistPopeList': '',
                            saleOrderList: [
                                { code: 'SO202403001', inWarehousePackNum: 1, positionId: null }
                            ]
                        }
                    ],
                    'qrCode': '',
                    'remark': '',
                    'saleAddress': '',
                    'typeCode': '',
                    'typeId': 1,
                    'typeName': '',
                    'warehouseCode': '',
                    'warehouseId': null,
                    'warehouseName': '',
                    'workshopCode': '',
                    'workshopId': null,
                    'workshopName': ''
                },
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    warehouseId: [{ required: true, trigger: 'change' }],
                    typeId: [{ required: true, trigger: 'change' }]
                },
                positionList: [],
                warehouseList: [],
                typeList: [
                    { id: 1, code: 'A', name: '自制成品入库' },
                    { id: 2, code: 'B', name: '下脚料入库' }
                ],
                deptList: [],
                defaultRowData: {
                    'processId': '',
                    'processCode': '',
                    'processName': '',
                    'unitPrice': null
                }
            };
        },
        methods: {
            onDeleteSaleOrderBtn(rowIndex, index) {
                this.ruleForm.packageInStorageItemList[rowIndex].saleOrderList.splice(index, 1);
            },
            onDeptChange(id, e) {
                this.$set(this.ruleForm, 'deptId', e.id);
                this.$set(this.ruleForm, 'deptCode', e.code);
                this.$set(this.ruleForm, 'deptName', e.name);
            },
            onWarehouseChange(e) {
                this.ruleForm.packageInStorageItemList.forEach(k => {
                    k.saleOrderList.forEach(x => {
                        this.$set(x, 'positionId', null);
                        this.$set(x, 'positionCode', '');
                        this.$set(x, 'positionName', '');
                    });
                });
                this.getPositionListRequest();
            },
            getPositionListRequest() {
                if (!this.ruleForm.warehouseId) return;
                spinPositionPage({
                    warehouseId: this.ruleForm.warehouseId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.positionList = res.data.res || [];
                    }
                });
            },
            onDeleteBtn(scope) {
                this.ruleForm.packageInStorageItemList.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.packageInStorageItemList.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;

                const warehouseItem = this.warehouseList.find(x => x.id === params.warehouseId) || {};
                params.warehouseCode = warehouseItem.code;
                params.warehouseName = warehouseItem.name;

                const typeItem = this.typeList.find(x => x.id === params.typeId) || {};
                params.typeeCode = typeItem.code;
                params.typeeName = typeItem.name;
                let positionItem = {};
                params.packageInStorageItemList.forEach(orderItem => {
                    positionItem = {};
                    orderItem.saleOrderList.forEach(saleOrderItem => {
                        positionItem = this.positionList.find(x => x.id === saleOrderItem.positionId) || {};
                        saleOrderItem.positionCode = positionItem.code;
                        saleOrderItem.positionName = positionItem.name;
                    });
                });
                if (!this.dataId) {
                    params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                productionPackageInStorageUpdate(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionPackageInStorageGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.packageInStorageItemList = resData.packageInStorageItemList || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getWarehouseListRequest() {
                return spinWarehousePage().then(res => {
                    if (res.data.status === 200) {
                        this.warehouseList = res.data.res || {};
                    }
                });
            },
            getDeptListRequest() {
                return listDept({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.deptList = res.data.res || {};
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$route.query.workshopId ? Number(this.$route.query.workshopId) : this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                await this.getDeptListRequest();
                await this.getWarehouseListRequest();
                if (this.dataId) await this.getDetailRequest();
                await this.getPositionListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.delete-icon {
    font-size: 13px;
    cursor: pointer;
    color: #2d8cf0;
    margin-left: 2px;
}
</style>
